package com.whenJay;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class down extends HelloServlet{
    // 这个类用于测试下载文件



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1 获取下载文件的路径
        String realPath = "F:\\JavaWeb_Learning\\target\\classes\\textImg\\img12.png";
        // 2 下载的文件名是啥？
        String fileName = realPath.substring(realPath.lastIndexOf("\\img12.png"));
        // 3 设置想办法让浏览器支持此下载我们需要的东西
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        // 4 获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        // 5 创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        // 6 获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        // 7 将FileOutStream流写入到buffer缓冲区
        while((len=in.read(buffer))>0){
            out.write(buffer,0,len);
        }
        in.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
